//
//  ST_QuickMessageTextViewController.swift
//  btvideo
//
//  添加常用语（文字）
//
//  Created by mac on 2021/9/7.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import RxSwift

class ST_QuickMessageTextViewController: UIViewController {

    /// 卡片背景
    let bgView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    
    /// 点击关闭弹窗手势
    lazy var dismiss_tap: UITapGestureRecognizer = {
        let tap = UITapGestureRecognizer()
        tap.delegate = self
        return tap
    }()
    
    /// 标题
    let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "添加常用语"
        label.textColor = UIColor(hexString: "#333333")
        label.font = .systemFont(ofSize: 18, weight: .medium)
        return label
    }()
    
    /// 关闭按钮
    let close_button: UIButton = {
        let button = UIButton()
        button.setImage(#imageLiteral(resourceName: "quickMessage_icon_close"), for: .normal)
        return button
    }()
    
    /// 输入框
    let textView: ST_MMTextView = {
        let textView = ST_MMTextView()
        textView.placeholder = "例：你好呀"
        textView.maximumLength = 100
        textView.font = .systemFont(ofSize: 14, weight: .medium)
        textView.cornerRadius = 10
        textView.borderColor = UIColor(hexString: "#E6E9EE")
        textView.borderWidth = 1
        textView.keyboardDistanceFromTextField = 88
        textView.tintColor = UIColor(hexString: "#FEC207")
        textView.textContainerInset = UIEdgeInsets(top: 15, left: 12, bottom: 15, right: 12)
        return textView
    }()
    
    /// 添加按钮
    let add_button: UIButton = {
        let button = UIButton(type: .system)
        button.setTitle("添加", for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = .systemFont(ofSize: 16, weight: .semibold)
        button.backgroundColor = UIColor(hexString: "#FEC207")
        button.cornerRadius = 22
        return button
    }()
    
    var disposeBag = DisposeBag()
    let viewModel = ST_QuickMessageTextViewModel()
    var onAdd: (() -> Void)? = nil
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        overCurrentContext = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        
        setup_views()
        bindRx()
        
        textView.becomeFirstResponder()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        bgView.roundCorners([.topLeft, .topRight], radius: 16)
    }
    
    @available(iOS 11.0, *)
    override func viewSafeAreaInsetsDidChange() {
        super.viewSafeAreaInsetsDidChange()
        
        bgView.snp.updateConstraints { make in
            make.height.equalTo(375 + view.safeAreaInsets.bottom)
        }
    }

    func setup_views() {
        
        view.addGestureRecognizer(dismiss_tap)
        
        view.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.leading.bottom.trailing.equalToSuperview()
            make.height.equalTo(375)
        }
        
        bgView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview()
            make.centerX.equalToSuperview()
            make.height.equalTo(65)
        }
        
        bgView.addSubview(close_button)
        close_button.snp.makeConstraints { make in
            make.centerY.equalTo(titleLabel)
            make.trailing.equalToSuperview().inset(20)
        }
        
        bgView.addSubview(textView)
        textView.snp.makeConstraints { make in
            make.top.equalTo(titleLabel.snp.bottom)
            make.leading.trailing.equalToSuperview().inset(20)
            make.height.equalTo(80)
        }
        
        bgView.addSubview(add_button)
        add_button.snp.makeConstraints { make in
            make.top.equalTo(textView.snp.bottom).offset(20)
            make.leading.trailing.equalTo(textView).inset(18)
            make.height.equalTo(44)
        }
    }

    func bindRx() {
        
        dismiss_tap.rx.event
            .filter { $0.state == .ended }
            .asDriver(onErrorJustReturn: dismiss_tap)
            .drive(onNext: { [weak self] _ in
                self?.dismiss(animated: true)
            })
            .disposed(by: disposeBag)
        
        textView.rx.text.orEmpty
            .bind(to: viewModel.content)
            .disposed(by: disposeBag)
        
        close_button.rx.tap
            .subscribe(onNext: { [weak self] in
                self?.dismiss(animated: true)
            })
            .disposed(by: disposeBag)
        
        add_button.rx.tap
            .subscribe(onNext: { [weak self] in
                self?.add()
            })
            .disposed(by: disposeBag)
    }
    
    /// 添加常用语
    func add() {
        show_indeterminate_h_u_d()
        viewModel.add()
            .subscribe(onSuccess: { [weak self] in
                self?.toast(text: "添加成功")
                self?.onAdd?()
                self?.dismiss(animated: true)
            }, onError: { [weak self] error in
                self?.toast(text: error.localizedDescription)
            })
            .disposed(by: disposeBag)
    }
}

extension ST_QuickMessageTextViewController: UIGestureRecognizerDelegate {
    
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        // 点击的view为self.view才响应tap手势
        touch.view == view
    }
}
